var exp = "{\n" +
    "    \"type\": \"PUT\",\n" +
    "    \"params\": {\n" +
    "        \"content-type\": \"json\"\n" +
    "    },\n" +
    "    \"headers\": {\n" +
    "        \"content-type\": \"json\"\n" +
    "    },\n" +
    "    \"body\": {\n" +
    "        \"formData\": {\n" +
    "            \"content-type\": \"json\",\n" +
    "            \"test\": \"123456\"\n" +
    "        },\n" +
    "        \"formUrlEncoded\": null,\n" +
    "        \"raw\": null,\n" +
    "        \"file\": null\n" +
    "    }\n" +
    "}";

function fillDataTemplete(data) {
    var jsonString = JSON.parse(exp);
    jsonString.type = data.type;
    jsonString.params = data.params;
    jsonString.headers = data.headers;
    jsonString.body = data.body;
    return jsonString;
}

function showJsonEditor(elementId) {
    var jsonString = JSON.parse(exp);
    // create the editor
    var container = document.getElementById(elementId);
    var options = {
        mode: 'code',
        modes: ['code', 'form', 'text', 'tree', 'view'], // allowed modes
        onError: function (err) {
            alert(err.toString());
        }
    };
    return new JSONEditor(container, options, jsonString);
}

var addModalJsonEditor = showJsonEditor("jsonEditor_add");
var updateModalJsonEditor = showJsonEditor("jsonEditor_update");

function addInterfaceModalShow() {

    $.ajax({
        url: "/flytest/proj/projects",
        type: "get",
        dataType: "json",
        success: function (result) {
            console.log(result);
            var projects = result.projects;
            var select = document.getElementById('belongProject');
            var option = "";
            for (var i = 0; i < projects.length; i++) {
                option = option + "<option value=\"{projectId}\">{projectName}</option>".signMix(projects[i])
            }

            select.innerHTML = option;
        }
    });
}

function updateInterfaceModalShow(interfaceId) {
    var exampleId = '';
    $.ajax({
        url: "/flytest/proj/projects",
        type: "get",
        dataType: "json",
        async: false,
        success: function (result) {
            console.log(result);
            var projects = result.projects;
            var select = document.getElementById('belongProject_update');
            var option = "";
            for (var i = 0; i < projects.length; i++) {
                option = option + "<option value=\"{projectId}\">{projectName}</option>".signMix(projects[i])
            }
            select.innerHTML = option;
        }
    });

    $.ajax({
        url: "/flytest/proj/interface?interfaceId=" + interfaceId,
        type: "get",
        async: false,
        dataType: "json",
        success: function (result) {
            console.log(result);
            exampleId = result.interface.exampleId;
            $("#interfaceId_update").val(result.interface.interfaceId);
            $("#interfaceName_update").val(result.interface.interfaceName);
            $("#interfaceUrl_update").val(result.interface.uri);
            $("#belongProject_update").val(result.interface.belongTo);
            $("#example_update").val(result.interface.exampleId);
        }
    });

    $.ajax({
        url: "/flytest/mongo/interface?id=" + exampleId,
        type: "get",
        dataType: "json",
        success: function (result) {
            console.log(result);
            var json = fillDataTemplete(result.info);
            updateJsonEditor().set(json);
        }
    });
}

function addJsonEditor() {
    return addModalJsonEditor;
}

function updateJsonEditor() {
    return updateModalJsonEditor;
}

function addInterface() {
    // var exp = "{\"interfaceId\":null,\"interfaceName\":\"\",\"uri\":\"demo/id\",\"belongTo\":1,\"project\":null,\"exampleId\":null,\"type\":\"PUT\",\"params\":{\"content-type\":\"json\"},\"headers\":{\"content-type\":\"json\"},\"body\":{\"formData\":{\"password\":\"123456\",\"username\":\"root\"},\"formUrlEncoded\":null,\"raw\":null,\"file\":null}}\n";
    // var json = JSON.parse(exp);
    // json.interfaceName = $("#interfaceName_a").val();
    // json.uri = $("#interfaceUrl").val();
    // json.belongTo = $("#belongProject").val();

    var info = addJsonEditor().get();
    var data = JSON.stringify(info);
    console.log('++++++++++++++++++ data +++++++++++++++++++');
    console.log(data);
    var exampleId = '';
    //mongodb中新增info，并获得example id
    $.ajax({
        url: '/flytest/mongo/interface',
        type: 'post',
        async: false,
        data: data,
        contentType: "application/json",
        dataType: 'json',
        success: function (res) {
            //console.log(res);
            exampleId = res.interfaceInfo.exampleId;
        }
    });

    // 向mysql中添加interface
    var formData = $("#interface_add_form").serialize();
    formData = formData + exampleId;
    //console.log(formData);
    $.ajax({
        url: '/flytest/proj/interface',
        type: 'post',
        data: formData,
        dataType: 'json',
        success: function (res) {
            //console.log(res);
            if (res.code === '200') {
                window.location.href = '/flytest/proj/interfaces'
            }
        }
    })
}

function updateInterface() {

    var info = updateJsonEditor().get();
    info._id = $("#example_update").val();
    console.log('++++++++++++++++ update info start +++++++++++++++++++++');
    console.log(info);
    var data = JSON.stringify(info);
    $.ajax({
        url: '/flytest/mongo/interface',
        type: 'put',
        async: false,
        data: data,
        contentType: "application/json",
        dataType: 'json',
        success: function (res) {
            //console.log(res);
        }
    });
    console.log('++++++++++++++++ update info end +++++++++++++++++++++');

    var formData = $("#interface_update_form").serialize();
    console.log('-------------update interface start-----------');
    console.log(formData);

    $.ajax({
        url: '/flytest/proj/interface',
        type: 'put',
        data: formData,
        dataType: 'json',
        success: function (res) {
            //console.log(res);
            if (res.code === '200') {
                window.location.href = '/flytest/proj/interfaces'
            }
        }
    });
    console.log('-------------update interface end-----------');
}

$("button[name='deleteInterfaceBtn']").click(function () {
    var interfaceId = $(this).attr('interfaceid');
    var exampleId = $(this).attr('exampleid');

    bootbox.confirm({
        message: "确认删除接口吗？",
        buttons: {
            confirm: {
                label: 'Yes',
                className: 'btn-success'
            },
            cancel: {
                label: 'No',
                className: 'btn-danger'
            }
        },
        callback: function (result) {
            if (result) {
                removeInterface(interfaceId, exampleId);
                window.location.href = '/flytest/proj/interfaces';
            }
        }
    });

});

// 根据id删除接口
function removeInterface(interfaceId, exampleId) {
    console.log("start remove interface: " + interfaceId);
    $.ajax({
        url: '/flytest/proj/interface?id=' + interfaceId,
        type: 'delete',
        dataType: 'json'
    });

    console.log("start remove interface info: " + exampleId);
    $.ajax({
        url: '/flytest/mongo/interface?id=' + exampleId,
        type: 'delete',
        dataType: 'json',
        success: function (res) {
        }
    });


}

